package com.rising.face.ali.bishi.auctionsystem;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: rising
 * @Description:
 * @Date: create in 2021/2/28 11:50
 */
public class AuctionSystem {

    //商品价格
    private int commodityPrice;
    //商品名称
    private String commodityName;
    //最终竞拍次数，当达到这个值后，竞拍结束
    private int finalAuctionTimes;
    //竞拍次数
    private AtomicInteger auctionTimes = new AtomicInteger(0);
    //竞拍价格，默认是商品价格
    private AtomicInteger auctionPrice;
    //存放每个客户叫价次数
    private ThreadLocal<Integer> threadLocal = new ThreadLocal<>();

    private Object lock = new Object();

    //随机出价
    private Random random = new Random();


    public AuctionSystem() {
    }

    public AuctionSystem(int commodityPrice, String commodityName, int finalAuctionTimes) {
        this.commodityPrice = commodityPrice;
        this.commodityName = commodityName;
        this.finalAuctionTimes = finalAuctionTimes;
        auctionPrice = new AtomicInteger(commodityPrice);
    }

    public void auctionCommodity() {
        //当前用户
        String name = Thread.currentThread().getName();
        while (true) {
            synchronized (lock) {
                //已经达到最终竞拍次数，则终止竞拍
                if (auctionTimes.get() == finalAuctionTimes) {
                    return;
                }

                //每次加价在1-200之间
                int price = random.nextInt(200) + 1;
                int newPrice = auctionPrice.addAndGet(price);
                int currentAuctionTimes = auctionTimes.incrementAndGet();
                Integer integer = threadLocal.get();
                if (integer == null || integer.intValue() == 0) {
                    threadLocal.set(1);
                } else {
                    threadLocal.set(threadLocal.get() + 1);
                }
                System.out.println("客户：" + name + "第" + threadLocal.get() + "次出价， 加价：" + price +" 出价：" + newPrice + " 竞拍次数：" + currentAuctionTimes);
                if (auctionTimes.get() == finalAuctionTimes) {
                    System.out.println("------------------------恭喜------------------------");
                    System.out.println("客户：" + name + " 出价：" + newPrice + " 竞拍次数：" + currentAuctionTimes
                            + " 获得价值" + commodityPrice + "元的" + commodityName);
                }

                //自己出价后需要将其他人唤醒
                lock.notifyAll();
                try {
                    //出价一次后，必须自我等待，否则就会出现连续出价的情况
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //lock.notifyAll();
            }
        }
    }
}
